<?php


namespace App\Http\Controllers\Api;


use App\Jobs\Attachment\VideoCosReviewSubmit;
use App\Lib\Uploads\UploadHandler;
use App\Models\WxAttachment;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\FileUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use Illuminate\Http\Request;
use QCloud\COSSTS\Sts;


class UploadsController extends BaseController
{

    public function cos_tmp_callback(Request $request){
        $uid = $request->uid;
        $key = _empty_default_($request->key, '');
        if(_empty_($key)){
            return $this->fail(200001);
        }
        if(strpos($key, $uid . '/') === false){
            return $this->fail(200004);
        }
        $res_data = _empty_default_($request->data, []);
        if(_empty_($res_data)){
            return $this->fail(200001);
        }
        if($res_data['statusCode'] != 200){
            return $this->fail(200004);
        }
        $ossType = Settings::get('ossType');
        $cosConfig = Settings::get('cosv5', []);
        $model = new WxAttachment();
        $model->user_id = $uid;
        $model->path = $key;
        $model->domain = $cosConfig['domain'];
        $model->store_type = $ossType;

        $types_str = implode('|', FieldUtils::getAttachmentTypes());
        preg_match('/\.('.$types_str.')$/', $key, $matchs);
        if($matchs && _array_key($matchs, 1, null)){
            $model->type = $matchs[1];
        }else{
            $model->type = '';
        }
        if(in_array($model->type, ['mp4', 'mp3'])){
            $model->cos_review = 4;
        }

        $model->state = 0;
        $r = $model->save();
        if($r){
            if($model->cos_review == 4){
                VideoCosReviewSubmit::dispatch($model->id);
            }
            return $this->success(['url'=>$cosConfig['domain'] . '/' . $key]);
        }else{
            return $this->fail(200002);
        }
    }

    public function cos_tmp_credentials(Request $request){
        $uid = $request->uid;
        $action = _empty_default_($request->action, 'put');
        $sts = new Sts();

        $cosConfig = Settings::get('cosv5', []);
        if(_empty_(_array_key($cosConfig, 'secretKey', ''))){
            return $this->fail(200008, [], 'cos配置错误');
        }
        $config = [];
        if($action == 'put'){
            $config = [
                'url' => 'https://sts.tencentcloudapi.com/',
                'domain' => 'sts.tencentcloudapi.com',
                'secretId' => $cosConfig['secretId'], // 替换为您的 SecretId
                'secretKey' => $cosConfig['secretKey'], // 替换为您的 SecretKey
                'bucket' => $cosConfig['bucket'] . '-' . $cosConfig['appId'], // 替换为您的 bucket
                'region' => $cosConfig['region'], // 替换为您的 bucket 所在地区
                'durationSeconds' => 1800, // 密钥有效期，单位/秒，默认半小时
                'allowPrefix' => [date('Y/m/d'). '/' . $uid . '/*'], // 临时密钥允许的前缀
                'allowActions' => ['name/cos:PutObject', 'name/cos:PostObject'] // 临时密钥允许的操作列表
            ];
        }else if($action == 'post'){
            $config = [
                'url' => 'https://sts.tencentcloudapi.com/',
                'domain' => 'sts.tencentcloudapi.com',
                'secretId' => $cosConfig['secretId'], // 替换为您的 SecretId
                'secretKey' => $cosConfig['secretKey'], // 替换为您的 SecretKey
                'bucket' => $cosConfig['bucket'] . '-' . $cosConfig['appId'], // 替换为您的 bucket
                'region' => $cosConfig['region'], // 替换为您的 bucket 所在地区
                'durationSeconds' => 1800, // 密钥有效期，单位/秒，默认半小时
                'allowPrefix' => [date('Y/m/d'). '/' . $uid . '/*'], // 临时密钥允许的前缀
                'allowActions' => ['name/cos:PostObject'] // 临时密钥允许的操作列表
            ];
        }
        if(_empty_($config)){
            return $this->fail(200004);
        }
        // 传入配置获取cos临时密钥
        $result = $sts->getTempKeys($config);
        return $this->success($result);
    }

    public function putFile(Request $request)
    {
        $uid = $request->uid;

        _limit_user('user:upload:file', $uid, 18);

//        if(!UserUtils::is_user_can_upload($uid)){
//            return $this->fail(200000);
//        }
        $file = $request->file('file');
        $scene = $request->header('scene',0);

        if(!in_array($file->extension(), FieldUtils::getAttachmentTypes())){
            if(!in_array($file->getClientOriginalExtension(), FieldUtils::getAttachmentTypes())){
                _logger_(__file__, __line__, $file->extension());
                _logger_(__file__, __line__, $file->getClientOriginalExtension());
                return $this->fail(200022);
            }
        }

        $path = UploadHandler::handle($file, $uid, 0, $scene);
        if($path){
            return $this->success($path['url']);
        }else{
            return $this->fail(200017);
        }
    }

    public function delFile(Request $request){
        $uid = $request->uid;
        $url = $request->url;

        if(_empty_($url)){
            return $this->fail(200001);
        }

        $attachment_part = FileUtils::get_attachment_part_from_url($url);
        if($attachment_part){
            $the_attachment = WxAttachment::where([
                ['domain', '=', $attachment_part['domain']],
                ['path', '=', $attachment_part['path']]
            ])->first();

            if($the_attachment){

                $author_id = $the_attachment->user_id;
                if($author_id == $uid || UserUtils::is_mini_admin($uid)){
                    if(UploadHandler::del($the_attachment)){
                        return $this->success();
                    }else{
                        _logger_(__file__, __line__, $the_attachment);
                        return $this->fail(200006);
                    }
                }else{
                    return $this->fail(200000, [], '你没有上传权限');
                }

            }
            return $this->fail(200003);

        }
        return $this->fail(200004);

    }

}
